package com.heima.media.task;

import com.heima.media.service.IAuditService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.INTERNAL;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2021-12-26 12:20
 */
@Component
@Slf4j
@Async
public class MediaTask {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    /**
     * 监听到延迟消息任务任务：发布文章
     */
    public void handlMessage() {
        try {
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("article-publish");
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //初始化测试一条消息
            delayedQueue.offer("init", 1, TimeUnit.SECONDS);
            //监听消息
            while (true) {
                //如果没有监听消息，进入30秒阻塞
                String result = blockingDeque.poll(30, TimeUnit.SECONDS);
                if (StringUtils.isNotBlank(result) && !"init".equals(result)) {
                    System.out.println("接收到延迟发消息内容，延迟要发布文章ID：" + result);
                    int newsID = Integer.parseInt(result);
                    //调用自动审核业务代码
                    auditService.audit(newsID);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("消费者消费消息失败：", e);
        }

    }
}